﻿using System;
using System.Collections;

namespace Data_Storages
{
    public class DSNetClient : IDataStorage
    {
        private NetClient netClient = new NetClient();
        public event EventHandler<NetClientMessageEventArgs> MessageReceived;

        public DSNetClient(string host, int port)
        {
            netClient.MessageEvent += new EventHandler<NetClientMessageEventArgs>(netClientOnMessageEvent);
            if (!netClient.Login(host, port))
            {
                throw new Exception("Error while logging in");
            }
        }

        ~DSNetClient()
        {
            if (!Disconnect())
            {
                throw new Exception("Error while disconnecting");
            }
            else
            {
                netClient = null;
            }
        }

        private bool Disconnect()
        {
            if (netClient != null && netClient.Connected)
            {
                return netClient.Logout();
            }
            else
            {
                return true;
            }
        }

        private void netClientOnMessageEvent(object sender, NetClientMessageEventArgs e)
        {
            OnMessageEvent(e);
        }

        protected virtual void OnMessageEvent(NetClientMessageEventArgs args)
        {
            EventHandler<NetClientMessageEventArgs> handler = MessageReceived;
            if (handler != null)
            {
                handler(this, args);
            }
        }

        public void Save(ArrayList data)
        {
            byte[] message = null;
            if (!netClient.Send(message))
            {
                throw new Exception("Error while sending data");
            }
        }

        public ArrayList Load()
        {
            byte[] message = netClient.Receive();
            if (message == null)
            {
                throw new Exception("Error while receiving data");
            }
            var al = new ArrayList();
            return al;
        }
    }
}
